package com.sudo.common.ip2region;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.IOException;

/**
 * @Author：DayDayUp
 * @Create：2023/2/6 9:35
 */
@Slf4j
public class Ip2RegionByFile implements Ip2RegionStrategy {

    private Searcher searcher;

    public Ip2RegionByFile(String dbFile) {
        try {
            // 1、创建 searcher 对象
            searcher = Searcher.newWithFileOnly(dbFile);
        } catch (IOException e) {
            log.error("failed to create searcher with `{}`：", dbFile, e);
        }
    }

    @Override
    public String search(String ip) {
        // 2、查询
        try {
            return searcher.search(ip);
        } catch (Exception e) {
            log.error("Ip2RegionByFile ip转换异常",e);
            return null;
        }
    }

    @Override
    public void destroy() throws Exception {
        // 3、关闭资源
        searcher.close();
    }
}
